//
//  GSTexture.cpp
//  GSEngine
//
//  Created by Александр on 02.02.14.
//  Copyright (c) 2014 SNK. All rights reserved.
//

#include "GSTexture.h"

namespace GSEngine
{
    GSTexture::GSTexture():m_textureType(ETexture2d), m_textureFormat(ETextureBMP), m_size(0,0), m_bitPerPixel(0), m_info(nullptr), m_data(nullptr), m_isLoaded(false)
    {

    }
    GSTexture::GSTexture(ETextureFormat format):m_textureType(ETexture2d), m_textureFormat(format), m_size(0,0), m_bitPerPixel(0)
    {
        
    }
    GSTexture::~GSTexture()
    {
        if (m_info != nullptr)
            delete m_info;
        if (m_data != nullptr)
            delete m_data;
    }
    void GSTexture::loadTexture(const char* path, const char* permission)
    {
        m_file = fopen(path, permission);
        if (m_file != NULL)
        {
            if (m_textureFormat == ETextureBMP)
            {
               loadFromBMP(path, permission);
            }
        }
    }
    void GSTexture::loadFromBMP(const char* path, const char* permission)
    {
        m_info = new unsigned char [54];
        fread(m_info, sizeof(unsigned char), 54, m_file);
        m_size = vec2i(*(int*)&m_info[18], *(int*)&m_info[22]);
        m_bitPerPixel = *(int*)&m_info[28];
        
        int size = (m_bitPerPixel/8) * m_size.x * m_size.y;
        m_data = new unsigned char[size];
        fread(m_data, sizeof(unsigned char), size, m_file);
        fclose(m_file);
        for(int i = 0; i < size; i += 3)
        {
            unsigned char tmp = m_data[i];
            m_data[i] = m_data[i+2];
            m_data[i+2] = tmp;
        }
        m_isLoaded = true;
    }
    void GSTexture::loadFromPNG(const char* path, const char* permission)
    {
        
    }
    void GSTexture::loadFromJPG(const char* path, const char* permission)
    {
        
    }
    bool GSTexture::isLoadedTexture()
    {
        return m_isLoaded;
    }
    ETextureType GSTexture::getTextureType()
    {
        return m_textureType;
    }
    ETextureFormat GSTexture::getTextureFormat()
    {
        return m_textureFormat;
    }
    vec2i GSTexture::getSize()
    {
        return m_size;
    }
    int GSTexture::getBitPerPixel()
    {
        return m_bitPerPixel;
    }
    unsigned char* GSTexture::getData()
    {
        return m_data;
    }
}
